package com.tanhua.dubbo.api.mongo;

import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;

import java.util.List;

/**
 * 圈子互动服务实现类
 */
@DubboService
@Slf4j
public class CommentApiImpl implements CommentApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 圈子互动-评论列表分页查询
     *
     * @param page
     * @param pageSize
     * @param movementId
     * @return
     */
    @Override
    public PageResult<Comment> findPageComments(Long page, Long pageSize, String movementId) {
        //1查询总记录数
        Query query = new Query();
        query.addCriteria(
                Criteria.where("publishId").is(new ObjectId(movementId))
                .and("commentType").is(CommentType.COMMENT.getType())
        );
        long counts = mongoTemplate.count(query, Comment.class);
        //2当前页面数据
        query.limit(pageSize.intValue()).skip((page-1)*pageSize);
        //2.1 created评论时间最新的放最上面
        query.with(Sort.by(Sort.Direction.DESC,"created"));
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        //3返回PageResult
        return new PageResult<>(page,pageSize,counts,commentList);
    }

    /**
     * 评论：点赞 评论 喜欢
     *
     * @param comment
     * @return
     */
    @Override
    public Integer addComment(Comment comment) {
        ObjectId publishId = comment.getPublishId();//动态id
        //1.补全 动态评论表中 被评论人ID(作者id)  根据动态id查询动态表获取作者id
        Movement movement = mongoTemplate.findById(publishId, Movement.class);
        Long publishUserId = movement.getUserId();
        comment.setPublishUserId(publishUserId);
        comment.setCreated(System.currentTimeMillis());//发表时间
        mongoTemplate.insert(comment);
        //2.根据动态id更新动态表评论数量+1
        //方式一：
        /*Query query = new Query();
        Update update = new Update();
        query.addCriteria(Criteria.where("id").is(publishId));//动态主键id
        update.inc("commentCount",1);//每次增长+1
        mongoTemplate.updateFirst(query,update,Movement.class);

        //3.获取最新的评论数返回
        Movement newMovement = mongoTemplate.findById(publishId, Movement.class);
        return newMovement.getCommentCount();*/

        //方式二：
        return updateCountByPublishId(comment, publishId, 1);
    }

    /**
     * 更新数量 并返回公共方法
     * @param comment
     * @param publishId
     * @param i
     * @return
     */
    private Integer updateCountByPublishId(Comment comment, ObjectId publishId, int i) {
        Query query = new Query();
        Update update = new Update();
        query.addCriteria(Criteria.where("id").is(publishId));//动态主键id
        update.inc(getCollName(comment.getCommentType()), i);//每次增长+1
        FindAndModifyOptions findAndModifyOptions = new FindAndModifyOptions();
        findAndModifyOptions.returnNew(true);//自增长后 返回新的值
        Movement mm = mongoTemplate.findAndModify(query, update, findAndModifyOptions, Movement.class);
        return mm.statisCount(comment.getCommentType());
    }

    /**
     * 取消点赞 取消喜欢
     *
     * @param comment
     * @return
     */
    @Override
    public Integer deleteComment(Comment comment) {
        ObjectId publishId = comment.getPublishId();
        Integer commentType = comment.getCommentType();
        Long commentUserId = comment.getUserId();
        //1.根据publishId commentType userId删除点赞记录
        Query query = new Query();
        query.addCriteria(Criteria.where("publishId").is(publishId).and("commentType").is(commentType).and("userId").is(commentUserId));
        mongoTemplate.remove(query,Comment.class);
        //2.更新-1并返回
        return updateCountByPublishId(comment, publishId, -1);
    }

    /**
     * 通过评论类型，获取要更新的动态表中的列名
     * @param commentType
     * @return
     */
    private String getCollName(int commentType){
        if(CommentType.LIKE.getType() == commentType){
            return "likeCount";
        }else if(CommentType.COMMENT.getType() == commentType){
            return "commentCount";
        }else{
            return "loveCount";
        }
    }
}
